package com.tbit.uqbike.client.remote;

import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;

/**
 * 网关reids客户端
 *
 * @author Leon
 * 2018年5月31日 下午7:57:00
 */
@Slf4j
@Configuration
public class GatewayRedisCinent {
    static JedisPool pool;

    /**
     * 反序列化
     *
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                bais.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }

        }
        return null;
    }

    /**
     * 获取二次哈希
     *
     * @param key
     * @param field
     * @return
     * @throws UnsupportedEncodingException
     */
    @SuppressWarnings("deprecation")
    public static String getSecondHash(String key, String field) {
        Jedis jedis = pool.getResource();
        try {
            byte[] result = jedis.hget(key.getBytes(), field.getBytes());
            if (result == null) {
                return null;
            }
            return (String) unserialize(result);
        } finally {
            pool.returnResource(jedis);
        }
    }

    public static String getSecondHashNew(String key, String field) {
        Jedis jedis = pool.getResource();
        try {
            byte[] result = jedis.hget(key.getBytes(), field.getBytes());
            if (result == null) {
                return null;
            }
            return (String) unserialize(result);
        } finally {
            pool.returnResource(jedis);
        }
    }

    @Autowired
    public void setPool(@Value("${redis-gateway.ip}") String ip, @Value("${redid-gateway.port}") Integer port) {
        GatewayRedisCinent.pool = new JedisPool(new JedisPoolConfig(), ip, port);
    }

}
